<?php
include('./common.php');

function update_list($jf, $np, $nt) {
    $jr = file_get_contents($jf);
    $jo = json_decode($jr, true);
    $jo[$np] = $nt;
    $je = json_encode($jo, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    $result = file_put_contents($jf, $je);
    return [
        'result' => $result,
        'list' => $jo
    ];
}

function generate_tree($web, $dir, $jf, $np, $nt=null) {
    $bd = $web . '/blog';
    $pattern = '/^' . str_replace('/', '\/', $bd) . '/i';
    $tl = update_list($jf, $np, $nt);
    $tl = $tl['list'];
    @ob_clean();
    listFolderFiles($dir, $pattern, $tl);
    $content = ob_get_contents();
    echo '这句没机会输出!哈哈';
    @ob_end_clean();
    @ob_flush();
    return $content;
}

@ob_clean();
header('Content-Type: application/json;charset=utf-8');
if(isLogined()) {
    $c = @$_REQUEST['content'];
    $rn = @$_REQUEST['name'];
    $nt = @$_REQUEST['title'];
    
    $web = dirname(dirname(dirname(__FILE__)));
    $jf = realpath('./list.json');
    $bd = $web . '/blog/';
    $sd = $web . '/source/';
    // 去掉开头的目录
    $pattern = '/^' . str_replace('/', '\/', $sd) . '/i';
    $p = preg_replace($pattern, '', $rn);
    // 去掉末尾的.md
    $n = substr($p, 0, -3) . '.html';
    $np = $n;
    if(strlen($n) > 0) {
        if(strlen(dirname($n)) > 0) {
            $anp = $bd . dirname($n);
            if(!file_exists($anp) || !is_dir($anp)) {
                mkdir($anp, 0777, true);
            }
        }
        $d = $bd . $n;
        $t = file_get_contents('./template.html');
        $content = str_replace('{{content}}', $c, $t);
        $content = str_replace('{{title}}', $nt, $content);
        $r = file_put_contents($d, $content);
        $lp = $bd . 'tree-list.txt';
        $tc = generate_tree($web, $bd, $jf, $np, $nt);
        $tr = file_put_contents($lp, $tc);
        $data = [
            'dist' => $d,
            'write' => $r,
            'tree' => $tr
        ];
    }
    else {
        $data = [];
    }
    
    echo json_encode($data);
}
else {
    echo '["login is required!"]';
}
@ob_flush();